package org.bee.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;

/**
 * S3文件上传工具
 */
@Component
public class S3Utils{
    private static final Logger log = LoggerFactory.getLogger(S3Utils.class);

    private final S3Client s3Client;

    public S3Utils(S3Client s3Client) {
        this.s3Client = s3Client;
    }

    /**
     * 上传文件(需注意，同名文件会被覆盖，而不会异常,上传的文件获取的访问链接是永久的)
     *
     * @param bucketName 存储桶名称
     * @param key        文件名称
     * @param bytes      文件字节数组
     * @param contentType 文件类型
     * @return 是否上传成功
     */
    public boolean uploadFile(String bucketName, String key,byte[] bytes, String contentType) {
        PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                .bucket(bucketName)
                .key(key)
                .contentType(contentType)
                .acl("public-read")
                .build();
        PutObjectResponse putObjectResponse = s3Client.putObject(putObjectRequest, RequestBody.fromBytes(bytes));
        return putObjectResponse.sdkHttpResponse().isSuccessful();
    }

    /**
     * 删除文件
     *
     * @param bucketName 存储桶名称
     * @param key        文件名称
     * @return 是否删除成功
     */
    public boolean deleteFile(String bucketName, String key) {
        DeleteObjectResponse deleteObjectResponse = s3Client.deleteObject(builder -> builder.bucket(bucketName).key(key));
        return deleteObjectResponse.sdkHttpResponse().isSuccessful();
    }

    /**
     * 获取文件访问链接
     *
     * @param bucketName 存储桶名称
     * @param key        文件名称
     * @return 文件访问链接
     */
    public String getFileUrl(String bucketName, String key) {
        return s3Client.utilities().getUrl(builder -> builder.bucket(bucketName).key(key)).toString();
    }
}
